import 'package:fluent_ui/fluent_ui.dart';
import 'package:flutter/material.dart' as Mat;
import 'package:flutter_editor/models/file_list_model.dart';
//import 'package:flutter/material.dart';
//import 'package:flutter_simple_treeview/flutter_simple_treeview.dart';
//import 'package:flutter_editor/components/tree_from_json.dart';

typedef CreateCallback = void Function(String);

// Tree View
class FileTreeView extends StatefulWidget {
  const FileTreeView({Key? key}) : super(key: key);

  @override
  _FileTreeView createState() => _FileTreeView();
}

// implementation for tree view
class _FileTreeView extends State<FileTreeView> {
  List<TreeViewItem> _items = [];

  // init state
  @override
  void initState() {
    super.initState();

    _items = [
      TreeViewItem(
          content: const Text(''), value: '', onInvoked: on_item_select)
    ];

    FileList.getInstance().addListener(() {
      debugPrint("value notifier is true");
      setState(() {
        build_items();
      });
    }, ['root_change']);
  }

  // build tree view items from data
  List<TreeViewItem> build_tree_items(List<FileDirItem> items) {
    List<TreeViewItem> ret = [];

    for (FileDirItem item in items) {
      ret.add(TreeViewItem(
          content: Text(item.name),
          value: item.path,
          onInvoked: on_item_select,
          children: build_tree_items(item.children)));
    }

    return ret;
  }

  void build_items() {
    _items = build_tree_items(FileList.getInstance().root?.children ?? []);
  }

  // on item selected
  Future<void> on_item_select(TreeViewItem item) async {
    String path = item.value;
    if (path == '') {
      return;
    }

    print('===>>>: Select path file: $path');
    FileList.getInstance().open(path);
  }

  // Show input dialog

  void on_add_file_directory(BuildContext context, CreateCallback callback) {
    String new_name = '';

    showDialog(
      context: context,
      builder: (_) => ContentDialog(
        title: const Mat.Material(child: Mat.Text('File/Directory Name?')),
        content: Mat.Material(
          child: Mat.TextField(
            onChanged: (value) {
              new_name = value;
            },
          ),
        ),
        actions: [
          Button(
            child: const Text('Ok'),
            onPressed: () {
              print('New file: $new_name');
              callback(new_name);
              Navigator.pop(context);
            },
          ),
          FilledButton(
            child: const Text('Cancel'),
            onPressed: () => Navigator.pop(context),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    print('=======================>>> FileTreeView!!!!');
    return Column(
      crossAxisAlignment: CrossAxisAlignment.end,
      children: [
        Container(
          padding: const EdgeInsets.only(bottom: 5.0, top: 5.0),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.end,
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              Tooltip(
                message: 'New file',
                child: IconButton(
                    onPressed: () {
                      print('Add ================>>');
                      on_add_file_directory(context, (name) {
                        FileList.getInstance().new_file(name);
                      });
                    },
                    icon: const Icon(FluentIcons.page_add)),
              ),
              Tooltip(
                message: 'New folder',
                child: IconButton(
                    onPressed: () {
                      print('Add ================>>');
                      on_add_file_directory(context, (name) {
                        FileList.getInstance().new_dir(name);
                      });
                    },
                    icon: const Icon(FluentIcons.fabric_new_folder)),
              ),
            ],
          ),
        ),
        Flexible(
          child: Container(
            constraints: const BoxConstraints(
              //minHeight: 380,
              //maxHeight: 380,
              maxWidth: 350,
            ),
            decoration: BoxDecoration(
              border: Border.all(color: FluentTheme.of(context).inactiveColor),
            ),
            child: TreeView(
              selectionMode: TreeViewSelectionMode.single,
              shrinkWrap: false,
              items: _items,
              onItemInvoked: (item) async => debugPrint('onItemInvoked: $item'),
              onSelectionChanged: (selectedItems) async => debugPrint(
                  'onSelectionChanged: ${selectedItems.map((i) => i.value)}'),
            ),
          ),
        )
      ],
    );
  }
}
